<template>
  <div>
    <div>
      <van-sticky>
        <van-nav-bar title="黑马头条 - 登录" />
        <van-form @submit="onSubmit">
          <van-field
            v-model="user.mobile"
            name="mobile"
            label="手机号"
            placeholder="请输入手机号"
            :rules="[
              {
                required: true,
                message: '请填写正确的手机号',
                pattern: /^1[3|4|5|7|8][0-9]{9}$/,
              },
            ]"
          />
          <van-field
            v-model="user.code"
            type="text"
            name="code"
            label="验证码"
            placeholder="请输入验证码"
            :rules="[
              {
                required: true,
                message: '请填写正确验证码',
                pattern: /^\d{6}$/,
              },
            ]"
          />
          <div style="margin: 16px">
            <van-button round block type="info" native-type="submit"
            :loading = "isloading"
            :disabled = "isloading "
            loading-text='登录中...'
              >登录</van-button
            >
          </div>
        </van-form>
      </van-sticky>
    </div>
    <div>
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
import { loginAPI } from '../../api/index'
import { mapMutations } from 'vuex'
export default {
  data () {
    return {
      user: {
        mobile: '',
        code: ''
      },
      isloading: false
    }
  },
  methods: {
    ...mapMutations('userModule', ['setRefreshToken', 'setToken']),
    async onSubmit (value) {
      this.isloading = true
      const [err, res] = await loginAPI(value)
      this.isloading = false
      if (err) return this.$Notify({ type: 'danger', message: '账号或验证码错误' })
      else this.$Notify({ type: 'success', message: '登录成功' })
      // 保存到vuex
      const { refresh_token, token } = res.data.data
      this.setRefreshToken(refresh_token)
      this.setToken(token)
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .van-nav-bar {
  background-color: #007bff;
  .van-nav-bar__title {
    color: white;
    font-size: 14px;
  }
}
</style>

